//是否需要显示下拉促销
var cx = frxs.getUrlParam("cx");
$(function () {
    getShopInfo();

    //loadTotal();


    $(".suobox").click(function () {
        search();
    });

    $(".qingkong").click(function () {
        $(".searchbox").val("购物车商品搜索");
        search();
    });

    //促销
    cuxiao();
    //促销活动弹窗居中
    dialog_M();
});

function getShopInfo() {
    //获取门店送货线路
    $.ajax({
        url: site_path+"pcorder/index/getShopLineRoad",
        type: "post",
        data: {},
        success: function (obj) {
            obj = $.parseJSON(obj);

            if (obj.SendW1 == 1) {
                $("#sw1").show();
            }
            if (obj.SendW2 == 1) {
                $("#sw2").show();
            }
            if (obj.SendW3 == 1) {
                $("#sw3").show();
            }
            if (obj.SendW4 == 1) {
                $("#sw4").show();
            }
            if (obj.SendW5 == 1) {
                $("#sw5").show();
            }
            if (obj.SendW6 == 1) {
                $("#sw6").show();
            }
            if (obj.SendW7 == 1) {
                $("#sw0").show();
            }

            $("#orderEndTime").text(obj.OrderEndTime.toString().substring(0, 5));
            if (obj.OrderEndTime2.toString() != "") {
                $("#orderEndTime2").text(obj.OrderEndTime2.toString().substring(0, 5));
            }
        }
    });

    //今天星期几突出显示
    var date = new Date();
    var index = date.getDay();
    $("#sw" + index).attr("style", "color: red;font-weight: bold;");

}

//清空购物车
function cartDelete(user_id) {
    //清空购物车
    $.ajax({
        url: site_path+"pcorder/index/delCart",
        type: "post",
        data: { user_id: user_id, is_all:1 },
        success: function (json) {
            var data = $.parseJSON(json);
            if (data.code == "200") {
				getTotalPrice();
                layer.closeAll();
                $("#cartCount").text("0");
                clearCartCookie();
                location.href = site_path+"pcorder/index/cart";
            } else {
                layer.alert(data.msg);
            }
        }
    });

}

//删除购物车
function delCart(user_id, productId) {
		$("#tr_"+productId).remove();
		getTotalPrice();
        layer.closeAll();
        //加载层
        layer.load(0, { shade: [0.3, '#000'] });

        //删除购物车
        $.ajax({
            url: site_path+"pcorder/index/delCart",
            type: "post",
            data: { user_id: user_id, m_id: productId },
            success: function (json) {
                var data = $.parseJSON(json);
                //layer.closeAll();
                if (data.code == "200") {
                    $("#tr_" + productId).remove();
                    layer.closeAll(); 
					window.location.reload();
                    if ($("#cartTable tr td").length == 0) {
                     //   location.href = site_path+"pcorder/index/cart";
                    } else {
                        //赠品计算
                        promotionGiftCode(data);
                    }
                } else {
                    layer.closeAll();
                    layer.alert(data.code);
                }
            }
        });

}
//删除收藏
function delCollect(user_id, productId) {
    //询问框
    layer.confirm('确定删除？', {
        btn: ['确定', '取消'] //按钮
    }, function () {
        layer.closeAll();
        //加载层
        layer.load(0, { shade: [0.3, '#000'] });

        //删除购物车
        $.ajax({
            url: site_path+"pcorder/index/delCollect",
            type: "post",
            data: { user_id: user_id, c_id: productId },
            success: function (json) {
                var data = $.parseJSON(json);
                //layer.closeAll();
                if (data.code == "200") {

                    layer.closeAll();
                    layer.msg('删除成功', { time: 1000 });
                        //location.href = site_path+"pcorder/index/collect";

                } else {
                    layer.closeAll();
                    layer.alert(data.code);
                }
            }
        });

    }, function () {
        layer.closeAll();
    });

}

//减
function subtract(user_id, productId) {
    var preQty = $("#ipt_" + productId).val();

    preQty = parseInt(preQty) - 1;
    if (preQty < 1) {
        preQty = 1;
    }

    $("#ipt_" + productId).val(parseInt(preQty));
    var autoVal = "productID_" + productId;
    eval("if(typeof " + autoVal + " != 'undefined'){clearTimeout(" + autoVal + ");}");
    //clearTimeout(_s);
    eval(autoVal + " = setTimeout(function () { preQtyChange(user_id, productId) }, 300);");
	loadTotal();
}

//加
var _s;
function add(id, productId) {
    var preQty = $("#ipt_" + productId).val();

    preQty = parseInt(preQty) + 1;
    $("#ipt_" + productId).val(parseInt(preQty));

    var autoVal = "productID_" + productId;
    eval("if(typeof " + autoVal + " != 'undefined'){clearTimeout(" + autoVal + ");}");
    //clearTimeout(_s);
    eval(autoVal + " = setTimeout(function () { preQtyChange(id, productId) }, 300);");
    //_s = setTimeout(function () { preQtyChange(id, productId) }, 500);
    //preQtyChange(id, productId);
	loadTotal();
}




//数值-备注 改变
function preQtyChange(id, productId) {
    var remark = frxs.filterText($("#remark_" + productId).val());
    var rreQty = $("#ipt_" + productId).val();
    if (!rreQty || isNaN(rreQty)) {
        rreQty = "1";
    }
    if (parseFloat(rreQty) <= 0) {
        rreQty = "1";
    }

    //加载层
    //   layer.load(0, { shade: [0.1, '#000'] });

    //修改购物车单条
    $.ajax({
        url: site_path+"pcorder/index/updateCartSingle",
        type: "post",
        data: {
            m_id: productId,
            user_id: id,
            total: parseInt(rreQty),
            remark: remark.replace(/'/g, '&apos;')
        },
        success: function (json) {
            var data = $.parseJSON(json);
            layer.closeAll();
            if (data.code != "200") {
                layer.alert(data.msg, function () {
                    location.href = site_path+"pcorder/index/cart";
                });
                $(".layui-layer-setwin a").click(function () {
                    location.href = site_path+"pcorder/index/cart";
                });
            }
            //赠品计算
            promotionGiftCode(data);
        }
    });
    loadTotal();
}

//显示移除赠品根据data
function promotionGiftCode(data) {
    //先移除赠品
    $("#tbody .clsgift").remove();
    if (data.length > 0) {
        var giftCode = "";
        $(data.data).each(function () {
            giftCode += "<tr class='clsgift' id=\"tr_" + this.ProductId + "\">";
            giftCode += "<td class=\"thd1\">0</td>";
            giftCode += "<td class=\"thd2\">" + this.SKU + "</td>";
            giftCode += "<td class=\"thd3\"><a href=\"../Product/Detail?productId=" + this.ProductId + "\">";
            if (this.IsGift == 1) {
                giftCode += "<span class=\"Givegif Givegif2\">赠</span>";
            } else if(this.IsGift==2) {
                giftCode += "<span class=\"Givegif Givegif2\">搭售</span>";
            }
            giftCode += "<div style=\"padding-left: 2px;border:none;white-space:nowrap;overflow:hidden; text-overflow:ellipsis;\" title=" + this.ProductName + ">" + this.ProductName+"</div>";
            giftCode += "</a></td>";
            giftCode += "<td class=\"thd4\">" + this.SaleUnit + "</td>";
            giftCode += "<td class=\"thd6\">" + parseFloat(this.SalePrice).toFixed(2) + "</td>";
            giftCode += "<td class=\"thd6\">" + parseFloat(parseFloat(this.SalePrice) * (1 + parseFloat(this.ShopAddPerc))).toFixed(2) + "</td>";
            giftCode += "<td class=\"thd6\">" + parseFloat(this.ShopAddPerc).toFixed(3) + "</td>";
            giftCode += "<td class=\"thd7\"><span>" + this.PreQty + "</span></td>";
            giftCode += "<td class=\"thd8\" style=\"text-align: right;\">" + this.SubAmt + "</td>";
            giftCode += "<td class=\"thd9\">" + this.PromotionShopPoint + "</td>";
            giftCode += "<td class=\"thd10\"></td>";
            giftCode += "<td class=\"thd11\"></td>";
            giftCode += "<td style=\"display: none\">" + this.PromotionShopPoint + "</td>";
            giftCode += "<td style=\"display: none\">" + this.ShopPoint + "</td>";
            giftCode += "<td style=\"display: none\">" + this.ProductId + "</td>";
            giftCode += "<td style=\"display: none\">" + this.BigPackingQty + "</td>";
            giftCode += "</tr>";

        });
        $("#tbody").append(giftCode);
        layer.closeAll();
    } else {
        //如果本来就没有赠品，这里删除没必要重新计算
        if ($(".sales").length > 0) {
            location.href = '../Order/Cart';
        } else {
            layer.closeAll();
        }
    }
    //计算总数
    //loadTotal();
    //序号重新排列
    trSortCode();
}



//计算总数
function loadTotal() {
    var totalProductCount = 0;
    var totalProductAmt = 0;
    var totalPoint = 0;
    var totalAddAmt = 0;
    if ($("#cartTable tr td").length > 2) {
        $("#cartTable tr").each(function () {
            //单价
            var salePrice = $(this).find("td:eq(5)").text();
            alert
            //数量
            var preQty = $(this).find("input[type='text']:eq(0)").val();

            //如果没有找到文本框值，按赠品的方式查找
            if (!preQty || isNaN(preQty)) {
                preQty = ($(this).find("td:eq(7)").text());
            }
            if (parseFloat(preQty) <= 0) {
                preQty = "0";
            }
            //小计
            preQty = parseFloat(preQty).toFixed(2);
            var subAmt = parseFloat(parseFloat(salePrice) * parseFloat(preQty)).toFixed(2);
            $(this).find("td:eq(8)").text(subAmt);

            //积分
            var promotionShopPoint = $(this).find("td:eq(12)").text();
            var shopPoint = $(this).find("td:eq(13)").text();

            var subPoint = 0;
            if (promotionShopPoint > 0) {
                subPoint = parseFloat(promotionShopPoint) * parseFloat(preQty);
            } else {
                if (shopPoint <= 0) {
                    shopPoint = 0;
                }
                subPoint = parseFloat(shopPoint) * parseFloat(preQty);
            }

            var bigPoint = $(this).find("td:eq(15)").text();
            subPoint = parseFloat(bigPoint) * subPoint;


            //积分赋值
            $(this).find("td:eq(9)").text(parseFloat(subPoint).toFixed(2));

            //零售价
            var sysPrice = $(this).find("td:eq(4)").text();
            //平台汇率
            var shopAddPerc = $(this).find("td:eq(6)").text();
            totalAddAmt += parseFloat(sysPrice) * preQty * parseFloat(shopAddPerc);


            //商品总数量
            totalProductCount += parseInt(preQty);
            //商品总金额
            totalProductAmt += parseFloat(subAmt);
            //总积分
            totalPoint += parseFloat(subPoint);

        });

        //商品总数量
        $("#totalProductCount").text(parseInt(totalProductCount));
        //商品总金额
        $("#totalProductAmt").text(parseFloat(totalProductAmt).toFixed(2));
        $("#totalProductAmt2").text("￥" + parseFloat(parseFloat(totalProductAmt) - parseFloat(totalAddAmt)).toFixed(2));
        //总积分
        $("#totalPoint").text(parseFloat(totalPoint).toFixed(2));
        //总平台费用
        $("#totalAddAmt").text("￥" + parseFloat(totalAddAmt).toFixed(2));
        //订单总金额
        $("#payAmount").text("￥" + parseFloat(totalProductAmt).toFixed(2));

		$(".zonge").val(parseFloat(totalProductAmt).toFixed(2));
        //单体行数
        $("#totalLineCount").text("单体行数：" + $("#cartTable tr").length);
        //总金额
        $("#payAmount1").text(parseFloat(totalProductAmt).toFixed(2) + " 元");
        //总数量2
        $("#totalProductCount1").text("总数量：" + parseInt(totalProductCount));

        //购物车是否是整数



        //保存CooKie
        //过期时间 30分钟
        var date = new Date();
        date.setTime(date.getTime() + (30 * 60 * 1000));

        //调用保存
        $.cookie("cartCount", totalProductCount.toString(), { path: "/", expires: date });
    } else {
        $("#cartCount").text("0");
        //保存CooKie
        //过期时间 30分钟
        var date = new Date();
        date.setTime(date.getTime() + (30 * 60 * 1000));

        //调用保存
        $.cookie("cartCount", "0", { path: "/", expires: date });
    }
}


//重新维护序号
function trSortCode() {
    $("#cartTable tr").each(function (i) {
        $(this).find("td:eq(0)").text(i + 1);
    });
}
//延时提交0.3秒
function submitOrderTimeout() {
    //禁用提交按钮
    $(".clsSubmit").prop("disabled", "disabled");
    setTimeout(submitOrder, 500);
};

//订单提交
function submitOrder() {
    //判断是否达到起订金额
    var totalProductAmt = $("#totalProductAmt").text();
    var mininumAmt = $("#MininumAmt").val();
    if (parseFloat(totalProductAmt) < parseFloat(mininumAmt)) {
        //询问框
        layer.confirm("订单起订金额为" + mininumAmt + "元，未达到起订金额的订单不能提交！", {
            btn: ['确认', '继续购物'], //按钮
            closeBtn: 0               //不显示关闭按钮
        }, function () {
            //释放提交按钮
            $(".clsSubmit").removeAttr("disabled");
            layer.closeAll();
        }, function () {
            //释放提交按钮
            $(".clsSubmit").removeAttr("disabled");
            layer.closeAll();
            //跳转
            window.location.href = site_path+'pcorder/index/index';
        });
    } else {
        var isChecked = false;
        //线路没有配送时间设置
        $("#pchecked .swcls").each(function () {
            if ($(this).is(":visible")) {
                isChecked = true;
            }
        });
        if (!isChecked) {
            layer.alert("线路没有配送时间设置！");
            return;
        }

        //加载层
        layer.load(0, { shade: [0.3, '#000'] });

        //检查是否存在未确认的订单
        $.ajax({
            url: "../Order/CheckOrder",
            type: "post",
            data: {},
            success: function (obj) {
                var isExist = $.parseJSON(obj).Data;
                var orderId = $.parseJSON(obj).Info;
                if (isExist == true) {
                    //统一合并订单不要覆盖
                    //合并订单
                    submitOrder1(orderId, false);
                } else {
                    //没有直接提交
                    submitOrder1("", false);
                }
            }
        });
    }
}

//订单提交
function submitOrder1(orderId, bDeleteOld) {

    var remark = frxs.filterText($("#remark").val());

    //订单提交
    $.ajax({
        url: "../Order/SubmitOrder",
        timeout: 60000,
        type: "post",
        data: {
            remark: remark.replace(/'/g, '&apos;'),
            orderId: orderId,
            bDeleteOld: bDeleteOld
        },
        success: function (obj) {
            layer.closeAll();
            obj = $.parseJSON(obj);
            if (obj.Flag == "0") {

                //保存CooKie
                //过期时间 30分钟
                var date = new Date();
                date.setTime(date.getTime() + (30 * 60 * 1000));
                //调用保存
                $.cookie("cartCount", "0", { path: "/", expires: date });

                layer.alert('订单提交成功', function () {
                    //加载层
                    layer.load(0, { shade: [0.3, '#000'] });
                    location.href = '../Order/OrderList';
                });
                $(".layui-layer-setwin a").click(function () {
                    //加载层
                    layer.load(0, { shade: [0.3, '#000'] });
                    location.href = '../Order/OrderList';
                });
            } else {
                //释放提交按钮
                $(".clsSubmit").removeAttr("disabled");
                layer.alert(obj.Info);
            }
        }
    });
}


//清空购物车
function resetCart(user_id) {
    if ($("#cartTable tr td").length <= 2) {
        layer.alert("购物车内没有商品");
    } else {
        //询问框
        layer.confirm('确定清空购物车？', {
            btn: ['清空', '取消'] //按钮
        }, function () {
            layer.closeAll();
            //加载层
            layer.load(0, { shade: [0.3, '#000'] });
            cartDelete(user_id);
        }, function () {
            layer.closeAll();
        });
    }
	loadTotal();
}


//搜索
function search() {
    var searchKey = $.trim($(".searchbox").val());
    if (searchKey != "购物车商品搜索" && searchKey != "") {
        $(".shopcart tr").each(function (i) {
            //第一行是头部
            if (i > 0) {
                var sku = $(this).find("td:eq(1)").text();
                var productName = $(this).find("td:eq(2)").text();
                if ($(this).find("td:eq(0)").text() != "") {
                    if (!(sku.indexOf(searchKey) > -1 || productName.indexOf(searchKey) > -1)) {
                        $(this).hide();
                    } else {
                        $(this).show();
                    }
                }
            }
        });

        var curColor = "#FFFFFF";
        var curI = 0;
        $(".shopcart tr").each(function (i) {
            if ($(this).css("display") != "none") {
                curColor = curColor == "#F7F7F7" ? "#FFFFFF" : "#F7F7F7";
                $(this).css("background", curColor);
                $(this).find("td:eq(0)").text(curI);
                curI++;
            }
        });
    } else {
        $(".shopcart tr").show();
        var curColor = "#FFFFFF";
        var curI = 0;
        $(".shopcart tr").each(function () {
            curColor = curColor == "#F7F7F7" ? "#FFFFFF" : "#F7F7F7";
            $(this).css("background", curColor);
            if ($(this).find("td:eq(0)").text() != "购物车空空如也") {
                $(this).find("td:eq(0)").text(curI);
            }
            curI++;
        });
    }
}


//促销方法开始
function cuxiao() {
    var kg = 0;
    $(".shopInfo .sales").click(function () {
        if (kg == 0) {
            $(".shopInfo .salesBox").stop().slideDown();
            $(".arrowbg2").show();
            $(".arrowbg").hide();
            kg = 1;
        } else {
            $(".shopInfo .salesBox").stop().slideUp();
            $(".arrowbg2").hide();
            $(".arrowbg").show();
            kg = 0;
        }
    });

    //是否加载显示
    if (cx == "true") {
        $(".shopInfo .salesBox").show();
        $(".shopInfo .sales").click();
    }
};

//关闭Dialog
function closeDialog() {
    $(".all").hide();
    $(".dialog").hide();
    $("html,body").css({ "overflow": "visible" });

    location.href = "../Order/Cart?cx=true";
}

//购物车页面,添加促销活动弹窗
function showPromotionDialog(promotionId) {
    $(".all").show();
    $(".dialog").show();
    $("html,body").css({ "overflow": "hidden" });
    $("iframe").attr("src", "../Promotion/CartDetailPromotion?promotionId=" + promotionId);
}

//促销活动弹窗居中
function dialog_M() {
    var w_h = $(window).height();
    var h = (w_h - $(".dialog").height()) / 2;
    var h2 = (w_h - $(".dialog2").height()) / 2;
    $(".dialog").css("top", h);
    $(".dialog2").css("top", h2);
    var w_w = $(window).width();
    var w = (w_w - $(".dialog").width()) / 2;
    $(".dialog").css("left", w);
}

/**
 * Created by jiali on 2017/2/23.
 */

var createOrderHttpHelper={
    s_url:configs.s_url+"pcorder/index/createOrder",
    params:'params={"api_key":"'+configs.api_key+'","user_id":"'+configs.user_id+'","api_sgin":"'+configs.api_sgin+'","client_type":2,"ver":13,',
    create:function(infos,deliver_time,deliver_time_end,address,tel,truename,price,total,remark){
        var params = createOrderHttpHelper.params+'"info":'+infos+',"remark":"'+remark+'","m":"t_26_order_info","address":"'+address+'","service":"Grain.createOrder","deliver_time":"'+deliver_time+'","deliver_time_end":"'+deliver_time_end+'","tel":"'+tel+'","truename":"'+truename+'","price":"'+price+'","total":"'+total+'"}';
        this.doPost(params);
    },

    doPost:function(params){
        var result = {};
        $.ajax({
            type:"post",
            url:this.s_url,
            dataType:'json',
            data:params,
            beforeSend:function(){
                Loading =layer.msg('努力加载中...', {icon: 16,shade: [0.5, '#f5f5f5'],scrollbar: false,offset: '40%', time:100000}) ;

            },
            success:function Response(data){
                layer.close(Loading);
                createOrderHttpHelper.callback(data);
            }
        });
        return result;
    },
    callback:function(obj){
        if(obj.code==200) {
			loadTotal();
            var op= layer.open({
                title: '温馨提示',
                content: '提交成功',
                yes:function(){
					getTotalPrice();
                    //清空购物车
                    $.ajax({
                        url: site_path+"pcorder/index/delCart",
                        type: "post",
                        data: { user_id: configs.user_id, is_all:1 },
                        success: function (json) {
                            var data = $.parseJSON(json);
                            if (data.code == "200") {
                                getTotalPrice();
                                location.href = site_path+"pcorder/index/orders";
                            } else {
                            }
							
                        }
                    });
                }
            });
        }else{
            alert(obj.msg);
        }
    }
}